package com.hk.rabbitmq.service;

import com.google.gson.Gson;
import com.hk.rabbitmq.domain.User;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
public class Json2UserMessageConverter implements MessageConverter {

    private static final Gson GSON = new Gson();

    @Override
    public Message toMessage(Object object, MessageProperties messageProperties) throws MessageConversionException {
        return new Message(GSON.toJson(object).getBytes(StandardCharsets.UTF_8));
    }

    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        return GSON.fromJson(new String(message.getBody(), StandardCharsets.UTF_8), User.class);
    }

}